class Tag < ActiveRecord::Base

  attr_protected []

  belongs_to :enterprise
  has_many :customer_tags  

  validates :name,
    :enterprise_id,
    :presence => true

  validates :name,
    :uniqueness  => {
      :scope => :enterprise_id
    }

  default_scope lambda { where( :enterprise_id => Enterprise.current_id ).order('ping_yin asc') }

  scope :start_with, lambda {|ping_yin| where(['ping_yin like ?', "#{ping_yin}%"])}

  before_save do |tag|
    tag.name = tag.name.upcase
    tag.ping_yin ||= Hz2py.do(tag.name).upcase
  end

  def self.find_or_create_by_name(name)
    if where(:name => name).any?
      where(:name => name).first  
    else
      Tag.create!(:name => name)
    end
  end

  def added_to_customers(customers)
    customers.each do |customer|
      customer_tags << CustomerTag.new(
        :tag_id => id,
        :customer_id => customer.id
      )
    end
    self
  end
end
